<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2018-07-25 11:39:58
 * @Description: 广告位管理
 * @LastEditors: 李志刚
 * @LastEditTime: 2022-04-30 09:19:32
 * @FilePath: /CoinCMF/app/Http/Controllers/Console/Content/AdposController.php
 */

namespace App\Http\Controllers\Console\Content;

use App\Exceptions\FireFlyException;
use App\Models\Content\Ad;
use Illuminate\Http\Request;
use App\Models\Content\Adpos;
use App\Http\Controllers\Controller;
use App\Http\Requests\BatchRequest;
use App\Http\Requests\Cms\AdPosRequest;
use App\Http\Requests\Cms\AdPosUpdateRequest;
use App\Http\Requests\DetailRequest;

class AdposController extends Controller
{
    public function getList(Request $request)
    {
        $key = $request->input('key','');
        $page = $request->input('page', 1);
        $size = $request->input('size', 10);
        $query = AdPos::where(function ($q) use ($key) {
            if ($key != '') {
                $q->where('name', 'like', '%' . $key . '%');
            }
        })->where('del_flag', 0);
        $count = $query->count();
        $list = $query->limit($size)->offset(($page - 1) * $size)->orderBy('id', 'desc')->get();
        $res = ['list' => $list, 'count' => $count];
        return $this->resJson(200, '成功', $res);
    }
    public function postCreate(AdPosRequest $request)
    {
        $data = $request->all();
        $create = ['name' => $data['name'], 'is_mobile' => $data['is_mobile']];
        Adpos::create($create);
        return $this->resJson(200, '成功');
    }
    public function getDetail(DetailRequest $request)
    {
        $detail_id = $request->input('detail_id');
        $detail = AdPos::findOrFail($detail_id);
        return $this->resJson(200, '成功', $detail);
    }
    public function postEdit(AdPosUpdateRequest $request)
    {
        $data = $request->all();
        $detail_id = $data['detail_id'];
        $update = ['name' => $data['name'], 'is_mobile' => $data['is_mobile']];
        Adpos::where('id', $detail_id)->update($update);
        return $this->resJson(200, '成功');
    }
    public function postRemove(BatchRequest $request)
    {
        $detail_id = $request->input('detail_id',[]);
        // 先查广告位下有没有广告，没有直接删除
        if (Ad::whereIn('pos_id', $detail_id)->where('del_flag',0)->count() > 0) {
            throw new FireFlyException(400, '广告位下有广告，请先移除广告');
        }
        Adpos::whereIn('id', $detail_id)->update(['del_flag'=>1]);
        return $this->resJson(200, '成功');
    }
}
